package com.sdy.healthcode.web.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.IdCardUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.healthcode.biz.constants.Constants;
import com.sdy.healthcode.biz.dto.BayonetManageDTO;
import com.sdy.healthcode.biz.model.BayonetManage;
import com.sdy.common.model.Response;
import com.sdy.healthcode.biz.model.BuildingManage;
import com.sdy.healthcode.biz.service.BayonetManageService;
import com.sdy.healthcode.biz.service.BuildingManageService;
import com.sdy.healthcode.biz.utils.CopyUtil;
import com.sdy.healthcode.web.config.AppConfig;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.sdy.mvc.controller.BaseController;

import javax.rmi.CORBA.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cgj
 * @since 2020-03-09
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@RequestMapping("/bayonetManage")
@Api(tags = "卡口管理接口")
public class BayonetManageController extends BaseController {
    @Autowired
    private BayonetManageService bayonetManageService;
    @Autowired
    private AppConfig appConfig;
    @Autowired
    private BuildingManageService buildingManageService;

    @GetMapping("/bayonetPage")
    @ApiOperation(value = "卡口例表页", response = BayonetManageDTO.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "bayonetName", value = "卡口名称")
    })
    public Response bayonetPage(String bayonetName, Page<BayonetManage> page) throws UnsupportedEncodingException {
        if (StringUtil.isNotBlank(bayonetName)) {
            bayonetName = URLDecoder.decode(bayonetName, StandardCharsets.UTF_8.name());
        }
        LambdaQueryWrapper<BayonetManage> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtil.isNotBlank(bayonetName), BayonetManage::getBayonetName, bayonetName)
                .orderByDesc(BayonetManage::getCreateTime);
        IPage<BayonetManage> pageResult = bayonetManageService.page(page, wrapper);
        List<BayonetManage> records = pageResult.getRecords();
        List<BayonetManageDTO> bayonetManageDTOs = CopyUtil.batchClone(records, BayonetManageDTO.class);
        List<Integer> buildings = records.stream().map(BayonetManage::getBuilding).collect(Collectors.toList());
        List<Integer> floors = records.stream().map(BayonetManage::getFloor).collect(Collectors.toList());
        List<Integer> departments = records.stream().map(BayonetManage::getDepartment).collect(Collectors.toList());
        List<BuildingManage> blist = buildingManageService.list(Wrappers.<BuildingManage>lambdaQuery().in(BuildingManage::getId, buildings));
        List<BuildingManage> flist = buildingManageService.list(Wrappers.<BuildingManage>lambdaQuery().in(BuildingManage::getId, floors));
        List<BuildingManage> dlist = buildingManageService.list(Wrappers.<BuildingManage>lambdaQuery().in(BuildingManage::getId, departments));
        for (int i = 0; i < records.size(); i++) {
            for (int j = 0; j < blist.size(); j++) {
                if (records.get(i).getBuilding() != null && records.get(i).getBuilding().equals(blist.get(j).getId())) {
                    bayonetManageDTOs.get(i).setBuildingStr(blist.get(j).getName());
                }
            }
            for (int k = 0; k < flist.size(); k++) {
                if (records.get(i).getFloor() != null && records.get(i).getFloor().equals(flist.get(k).getId())) {
                    bayonetManageDTOs.get(i).setFloorStr(flist.get(k).getName());
                }
            }
            for (int l = 0; l < dlist.size(); l++) {
                if (records.get(i).getDepartment() != null && records.get(i).getDepartment().equals(dlist.get(l).getId())) {
                    bayonetManageDTOs.get(i).setDepartmentStr(dlist.get(l).getName());
                }
            }
        }
        return Response.success(new Page<BayonetManageDTO>().setRecords(bayonetManageDTOs)
                .setCurrent(pageResult.getCurrent()).setSize(pageResult.getSize()).setTotal(pageResult.getTotal()));
    }

    @PostMapping("/deleteOne")
    @ApiOperation(value = "删除单条")
    @ApiImplicitParam(value = "删除单条数据", required = true)
    public Response deleteOne(Integer id) {
        boolean result = bayonetManageService.removeById(id);
        return Response.success(result);
    }

    /**
     * 图片下载
     * @param id
     * @param response
     * @throws IOException
     */
    @GetMapping("/downloadImage")
    @ApiOperation(value = "下载图片")
    public void downloadFile(Integer id , HttpServletResponse response ) throws IOException {
        BayonetManage one = bayonetManageService.lambdaQuery().eq(BayonetManage::getId, id).one();
        // 下载文件命名数据
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss") ;
        String time = dateFormat.format(date);
        String fileName = one.getBayonetName() + ".png";
        byte[] data = BufferStreamForByte(one.getQrpicturePath());
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();

        response.flushBuffer();
    }
    public static byte[] BufferStreamForByte(String spec) {
        byte[] content = null;
        try {
            BufferedInputStream bis = null;
            ByteArrayOutputStream out = null;
            try {
                FileInputStream input=new FileInputStream(spec);
                bis = new BufferedInputStream(input, 1024);
                byte[] bytes = new byte[1024];
                int len;
                out = new ByteArrayOutputStream();
                while ((len = bis.read(bytes)) > 0) {
                    out.write(bytes, 0, len);
                }
                bis.close();
                content = out.toByteArray();
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (out != null) {
                    out.close();
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return content;
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增")
    public Response<Boolean> save(HttpServletRequest request, @RequestBody @ApiParam(name = "bayonetManage",
            value = "实体类") BayonetManage bayonetManage) throws BizException {
        Assert.isBlank(bayonetManage.getBayonetName(), "请正确填写卡口名称!");
        Assert.isBlank(bayonetManage.getBayonetLeader(), "请正确填写卡口负责人信息!");
        Assert.isTrue(!bayonetManage.getPhone().matches(com.sdy.common.constant.Constants.REGEX_PHONE), "手机号格式错误!");
        Integer userId = getUserId(request, Constants.SESSION_WEB_USER_ID);
        Integer department = bayonetManage.getDepartment();
        List<BayonetManage> list = bayonetManageService.list(Wrappers.<BayonetManage>lambdaQuery().eq(BayonetManage::getDepartment, department));
        Assert.notTrue(list.isEmpty(), "该卡点信息已存在!");
        Boolean aBoolean = bayonetManageService.saveBayonet(userId, bayonetManage, appConfig.getDomain());
        return Response.success(aBoolean);
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public Response update(HttpServletRequest request, @RequestBody @ApiParam(name = "bayonetManage",
            value = "实体类") BayonetManage bayonetManage) throws BizException {
        Assert.isBlank(bayonetManage.getBayonetName(), "请正确填写卡口名称!");
        Assert.isBlank(bayonetManage.getBayonetLeader(), "请正确填写卡口负责人信息!");
        Assert.isTrue(!bayonetManage.getPhone().matches(com.sdy.common.constant.Constants.REGEX_PHONE), "手机号格式错误!");
        Integer userId = getUserId(request, Constants.SESSION_WEB_USER_ID);
        Integer department = bayonetManage.getDepartment();
        BayonetManage one = bayonetManageService.getOne(Wrappers.<BayonetManage>lambdaQuery().eq(BayonetManage::getDepartment, department));
        if (one != null && !one.getId().equals(bayonetManage.getId())) {
            Assert.isTrue(true, "该卡点信息已存在!");
        }
        Date date = new Date();
        if (null == bayonetManage.getState()) {
            bayonetManage.setUpdateUser(userId).setUpdateTime(date);
        }
        if (bayonetManage.getState() != null) {
            if (bayonetManage.getState() == 1) {
                bayonetManage.setState(0).setOperationUser(userId).setOperationTime(date);
            } else if (bayonetManage.getState() == 0) {
                bayonetManage.setState(1).setOperationUser(userId).setOperationTime(date);
            }
            bayonetManage.setOperationUser(userId).setOperationTime(date);
        }
        boolean result = bayonetManageService.updateById(bayonetManage);
        return Response.success(result);
    }


    @GetMapping("/downloadBayonetManage")
    @ApiOperation(value = "卡口数据导出")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "bayonetName", value = "卡口名称")
    })
    public void downloadStaff(HttpServletResponse response, String bayonetName) throws UnsupportedEncodingException {

        if (StringUtil.isNotBlank(bayonetName)) {
            bayonetName = URLDecoder.decode(bayonetName, StandardCharsets.UTF_8.name());
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            String date = sdf.format(new Date());
            LambdaQueryWrapper<BayonetManage> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(StringUtil.isNotBlank(bayonetName), BayonetManage::getBayonetName, bayonetName)
                    .orderByDesc(BayonetManage::getCreateTime);
            List<BayonetManage> list = bayonetManageService.list(wrapper);
            List<BayonetManageDTO> bayonetManageDTOS = CopyUtil.batchClone(list, BayonetManageDTO.class);
            List<BuildingManage> builds = buildingManageService.list();
            for (BayonetManageDTO l : bayonetManageDTOS) {
                if (l.getState() == 0) {
                    l.setStateStr("禁用");
                } else if (l.getState() == 1) {
                    l.setStateStr("启用");
                }
            }
            for (int i = 0; i < bayonetManageDTOS.size(); i++) {
                for (int j = 0; j < builds.size(); j++) {
                    if (bayonetManageDTOS.get(i).getBuilding() != null && bayonetManageDTOS.get(i).getBuilding().equals(builds.get(j).getId())) {
                        bayonetManageDTOS.get(i).setBuildingStr(builds.get(j).getName());
                    }
                    if (bayonetManageDTOS.get(i).getFloor() != null && bayonetManageDTOS.get(i).getFloor().equals(builds.get(j).getId())) {
                        bayonetManageDTOS.get(i).setFloorStr(builds.get(j).getName());
                    }
                    if (bayonetManageDTOS.get(i).getDepartment() != null && bayonetManageDTOS.get(i).getDepartment().equals(builds.get(j).getId())) {
                        bayonetManageDTOS.get(i).setDepartmentStr(builds.get(j).getName());
                    }
                }
            }
            log.info("--"+bayonetManageDTOS);
            String fileName = "卡口二维码数据-" + date + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            EasyExcel.write(response.getOutputStream(), BayonetManageDTO.class).sheet("卡口二维码数据导出").doWrite(bayonetManageDTOS);
        } catch (Exception e) {
            log.error("卡口二维码数据导出" + e.getMessage(), e);
        }
    }
}
